package com.dbq.fast.business.login;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.BuildConfig;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.FireBaseUserPurchaseTrack;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.login.api.LoginApi;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.business.LoginBiz;
import com.dbq.fast.business.product.event.FaceBookUserPurchaseTrack;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SystemUtil;
import com.dbq.fast.util.TimeOutHandler;

import java.util.concurrent.atomic.AtomicInteger;

import static com.dbq.fast.analysis.EventConstant.PARAM_NET_FAIL;
import static com.dbq.fast.analysis.EventConstant.PARAM_NET_NONE;
import static com.dbq.fast.analysis.EventConstant.PARAM_SERVER_CODE;
import static com.dbq.fast.analysis.EventConstant.PARAM_SERVER_FAIL;
import static com.dbq.fast.business.login.business.LoginBiz.LOGIN_TYPE_VISITOR;

public class LoginProgressActivity extends BaseActivity implements LoginBiz.LoginListener{

    LoginBiz loginBiz;
    static AtomicInteger mark;
    private TimeOutHandler timeOutHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //去除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏展示
        getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_progress);

        login();
    }

    @Override
    public void loginSuccess(CustomProfile profile) {
        profile.setOsVer(Build.VERSION.RELEASE);
        profile.setAppVer(BuildConfig.VERSION_NAME);
        //向服务器端提交登录信息，提交成功组装数据写入db
        LoginApi.getUserInfo(profile, new RemoteApiCallBack<CustomProfile>() {
            @Override
            public void onSuccess(CustomProfile profile) {
                if(mark != null) {
                    if (mark.get() == 2) {
                        return;
                    }
                    mark.set(1);
                }
                Log.e("vpn_log", "hi result profile: " + profile.toString());
                YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_LOGIN_SUCC);
                FaceBookUserPurchaseTrack.loginEvent();
                FireBaseUserPurchaseTrack.login(App.getContext(),profile.getLoginChannel()+"");
                ProgressDialogUtil.hideProgress();
                Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_login_success), Toast.LENGTH_SHORT).show();
                DatabaseManager.getInstance().saveProfile(profile);
                User.getInstance().init();
                configUserId();
//                UploadTokenUtil.sendFirebaseTokenToServer();

                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFail(int status, String message) {
                Bundle bundle = new Bundle();
                configUserId();
                if(mark != null) {
                    if (mark.get() == 2) {
                        bundle.putString("login_fail_reason", PARAM_NET_FAIL);
                        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_LOGIN_FAIL, bundle);
                        return;
                    }
                    mark.set(3);
                    if(!SystemUtil.isNetworkAvailable(App.getContext())){
                        bundle.putString("login_fail_reason", PARAM_NET_NONE);
                    }else {
                        bundle.putString("login_fail_reason", PARAM_SERVER_FAIL);
                        bundle.putString("login_fail_reason", PARAM_SERVER_CODE+status);
                    }
                    YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_LOGIN_FAIL, bundle);
                }
                ProgressDialogUtil.hideProgress();
                Toast.makeText(App.getContext(), "" + message, Toast.LENGTH_SHORT).show();

                setResult(RESULT_CANCELED);
                finish();
            }
        });
    }

    private void login(){
        ProgressDialogUtil.showProgress(this, "", getString(R.string.waiting));
        loginTimeOutHandler();
        if(loginBiz == null){
            loginBiz = new LoginBiz(LoginProgressActivity.this);
        }
        loginBiz.setLoginListener(this);
        loginBiz.login(LOGIN_TYPE_VISITOR);
    }

    private void loginTimeOutHandler() {
        if (mark == null) {
            mark = new AtomicInteger(0); //0：开始网络请求，1：网络请求成功，2：网络超时, 3：网络请求失败
        } else {
            mark.set(0);
        }
        if(timeOutHandler == null) {
            timeOutHandler = new TimeOutHandler();
        }
        timeOutHandler.setTimeOutListener(() -> {
            if(mark != null) {
                if (mark.get() == 1 || mark.get() == 3) {
                    return;
                }
                mark.set(2);
            }
            ProgressDialogUtil.hideProgress();
            if(isResume){
                runOnUiThread(() -> {
                    Toast.makeText(App.getContext(), App.getContext().getString(R.string.login_time_out), Toast.LENGTH_LONG).show();
                });
            }
            setResult(RESULT_CANCELED);
            finish();
        });
        timeOutHandler.startTiming();
    }

    /**
     * 配置log日志中的用户id
     */
    private void configUserId(){
        com.yiba.logutils.utils.LogConfig.setUid("".equals(User.getInstance().getAccount())? SystemUtil.getAndroidId(App.getContext()):User.getInstance().getAccount());
    }

    @Override
    protected void onDestroy() {
        ProgressDialogUtil.hideProgress();
        if(loginBiz != null){
            loginBiz.destory();
        }
        super.onDestroy();
    }

}
